<?php

namespace Authorization\Service;

use Zend\Permissions\Acl\Acl;
use Zend\Mvc\Router\RouteMatch;

class AuthorizationService {

    const ERROR_UNAUTHORIZED = 'unauthorized-access';
    const ANONYMOUS_ROLE = 'anonymous';
    const ANY_ROLE = 'any';

    /**
     * @var Acl 
     */
    private $acl;
    
    /**
     * @var String 
     */
    private $role;

    /**
     * @param RouteMatch $routeMatch
     * @return boolean
     */
    public function isGranted($controller, $action) {
        if (!$this->acl->hasResource($controller)) {
            return true; // TODO: maybe this should be allowed only for admin?
        }
        
        if ($this->acl->isAllowed($this->getRole(), $controller, $action)) {
            return true;
        }

        return false;
    }
    
    public function setRole($role) {
         $this->role = $role ?: self::ANONYMOUS_ROLE;
    }
    
    public function getRole() {
        return $this->role;
    }
    
    public function isAnonymous() {
        return $this->role == self::ANONYMOUS_ROLE;
    }
    
    public function setAcl(Acl $acl) {
        $this->acl = $acl;
    }
    
    public function setRolesTree($rolesTree) {
        // special roles
        $this->acl->addRole(self::ANY_ROLE);
        $this->acl->addRole(self::ANONYMOUS_ROLE);
        
        foreach ($rolesTree as $role => $parents) {
            $this->acl->addRole($role, $parents ?: 'any');
        }
    }

    public function setPermissions($permissions) {
        foreach ($permissions as $controller => $config) {
            $this->acl->addResource($controller);
            
            foreach ($config as $action => $role) {
                $this->acl->allow($role, $controller, $action);
            }
        }
    }

}

